package registry

import (
	"context"
	"database/sql"
	entsql "entgo.io/ent/dialect/sql"
	. "gitee.com/aldrice/monitor/configs"
	"gitee.com/aldrice/monitor/ent"
	"gitee.com/aldrice/monitor/ent/migrate"
)

var dbClient *sql.DB
var entClient *ent.Client

func SetEnt(c *ent.Client) {
	entClient = c
}

func Ent() *ent.Client {
	if entClient == nil {
		panic("ent not init")
	}
	return entClient
}

func SetDB(c *sql.DB) {
	dbClient = c
}

func DB() *sql.DB {
	if dbClient == nil {
		panic("db not init")
	}
	return dbClient
}

func InitEnt(ctx context.Context) (err error) {
	dbClient, err = sql.Open(Config.DB.Driver, Config.DB.Source)
	if err != nil {
		return err
	}
	dbClient.SetMaxIdleConns(Config.DB.MaxIdle)
	dbClient.SetMaxOpenConns(Config.DB.MaxOpen)

	drv := entsql.OpenDB(Config.DB.Driver, dbClient)
	entClient = ent.NewClient(ent.Driver(drv))

	if !Config.IsProd {
		entClient = entClient.Debug()
	}
	return entClient.Schema.Create(ctx,
		migrate.WithDropIndex(!Config.IsProd),
		migrate.WithDropColumn(!Config.IsProd),
	)
}
